package graphic;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;

import javax.swing.JComponent;

import Graph.Graph;
import Graph.optimalWay;
import Graph.pathway;

public class Car extends JComponent{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public int[][] graph;
	
	public int number;
	public pathway Way;
	public int way [] = new int [100];
	public int length;
	public Point point [];
	private int numThrough;
	private int current;
	private double x;
	private double y;
	private double speed = 3.0;
	private double tangens [] = new double [3];
	private double dx;
	private int next;
	
	public Car(Graph City, optimalWay rMap){
		point = City.getPoint();
		graph = City.getGraph();
		number = City.getNumber();
		Way = rMap.getCourse(City, 2, 15);
		this.way = Way.getRoute();
		this.length = Way.getLength();
		numThrough = 1;
		next = this.way[numThrough];
		current = this.way[0];
		x = point[current].x;
		y = point[current].y;
	}
	
	protected double[] getTangens(int nextVert, double x, double y){
		double tangens [] = new double[3];
		if(point[nextVert].y >= y) tangens[2] = 1.0;
		else tangens[2] = -1.0;
		
		if (point[nextVert].x < x) tangens[1] = -1.0;
		else if (point[nextVert].x > x) tangens[1] = 1.0;
		else if(x == point[nextVert].x) {
			return tangens;
		}
		tangens [0] = ((float) ((float) point[nextVert].y - y)) / ((float) ((float) point[nextVert].x - x));
		return tangens;
	}
	public void paintCar(Graphics g){
		Graphics2D g1 = (Graphics2D) g;
		if(numThrough < length){
			if(((x - point[next].x) * (x - point[next].x)  + (y - point[next].y) * (y - point[next].y)) < speed * speed){
				++numThrough;
				x = point[next].x;
				y = point[next].y;
				next = way[numThrough];
				if (numThrough != length){
					g1.setColor(Color.GREEN);
					g1.fillOval((int) x, (int) y, 5, 5);
				}
			} else {
				tangens = getTangens(next, x, y);
				if(tangens[1] == 0.0) {
					dx = 0;
					y += speed * tangens[2];
				} else {
					dx = speed * tangens[1] * Math.sqrt(1 / (1 + tangens[0] * tangens[0]));
					x += dx;
					y += tangens[0] * dx;
				}
				if (numThrough != length){
					g1.setColor(Color.GREEN);
					g1.fillOval((int) x, (int) y, 5, 5);
				}
			}
		} else ;
	}
}
